package com.example.online.servlet;


import com.example.online.service.UserService;


import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;



//  第一次进入
//      确认输入手机号正确，并且拿不到pwd字段，转发至jsp界面显示出输入密码框 最后点击忘记密码转入servlet
//  第二次进入
//      确认已拿到pwd字段，修改数据库密码，弹窗提示忘记成功并跳转至登陆界面
@WebServlet(name = "ForgotServlet",value = "/ForgotServlet")
public class ForgotServlet  extends HttpServlet{

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        UserService userService = new UserService();

        //获取前端数据
        String phone = req.getParameter("phone");
        String pwd = req.getParameter("pwd1");

        //过滤条件确认第一次进入
        // 确认验证码正确  确认手机号为已知客户 确认pwd字段为空
        if(CaptchaServlet.check(req, resp) && userService.isExistByPhone(phone) > 0 && pwd == null || pwd.isEmpty()){
            req.setAttribute("again",1);
            req.setAttribute("phone",phone);
            req.getRequestDispatcher("/forget.jsp").forward(req,resp);
        }else{
            //第二次从jsp过来时直接重置密码并提示重置成功或失败
            //最后转发至登陆界面
            int num = userService.updatePwdByPhone(pwd,phone);
            if(num > 0){
                req.setAttribute("forget",1);
                req.getRequestDispatcher("/login.jsp").forward(req,resp);
            }else{
                req.setAttribute("forget",0);
                req.getRequestDispatcher("/login.jsp").forward(req,resp);
            }
        }




    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }
}
